package es.pyros.antreader.logic;

import java.io.File;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class XMLParser {
	
	private static String path = "";
	private static File xmlFile = null;
	private static DocumentBuilderFactory dbFactory = null;
	private static DocumentBuilder dBuilder = null;
	private static Document doc = null;
	private static List<String> listadoTarget = null;
	
	public XMLParser(){
		listadoTarget = new ArrayList<String>();
	}
	
	public void procesaArchivo(String ruta)throws ParserConfigurationException, SAXException, IOException{
		path = ruta;
		xmlFile = new File(path);
		dbFactory = DocumentBuilderFactory.newInstance();
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(xmlFile);
		doc.getDocumentElement().normalize();
		System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
		NodeList nList = doc.getElementsByTagName("target");
		System.out.println("-----------------------");
		for (int temp = 0; temp < nList.getLength(); temp++) {
			 
			   Node nNode = nList.item(temp);
			   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
	 
			      Element eElement = (Element) nNode;
			      listadoTarget.add(getAttribute("name", eElement));
			      //System.out.println("First Name : " + getTagValue("firstname", eElement));
			      System.out.println("Target: "+ getAttribute("name", eElement));
			      
	 
			   }
			}
	}
	
	public List<String> getTags(){
		return listadoTarget;
	}
	
	@SuppressWarnings("unused")
	private static String getTagValue(String sTag, Element eElement) {
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
		Node nValue = (Node) nlList.item(0);
		return nValue.getNodeValue();
	}
	
	private static String getAttribute(String sAttr, Element eElement){
		return eElement.getAttribute(sAttr);
	}

	public void cierraArchivo() {
		//TODO
	}
	
}
